import { Card } from '@mui/material'
import './index.scss'
import { useCallback, useEffect, useRef, useState } from 'react'
import { Stage, Layer } from 'react-konva'
import Konva from 'konva'

const KonvaFuncTest = () => {
  const stageContainerRef = useRef(null)
  const stageRef = useRef(null)
  const layerRef = useRef(null)
  const [stageSize, setStageSize] = useState({
    width: 100,
    height: 100
  })

  useEffect(() => {
    const ob = new ResizeObserver((entries) => {
      for(let entry of entries) {
        const { width, height } = entry.contentRect
        setStageSize({
          width,
          height
        })
      }
    })
    ob.observe(stageContainerRef.current)
    const circle = new Konva.Circle({
      x: 2800,
      y: 700,
      radius: 70,
      fill: 'red',
      stroke: 'black',
      strokeWidth: 4
    })
    const circle2 = new Konva.Circle({
      x: 100,
      y: 700,
      radius: 70,
      fill: 'red',
      stroke: 'black',
      strokeWidth: 4
    })
    layerRef.current.add(circle)
    layerRef.current.add(circle2)
  }, [])

  const dragBoundFunc = useCallback((e) => {
    console.log(e)
    if (e.x <= -1975){
      e.x = -1975
    }
    if (e.x >= 0) {
      e.x = 0
    }
    return e
  }, [])

  return (
    <div className="konva-func-test">
      <Card className='stageContainer' ref={stageContainerRef}>
        <Stage ref={stageRef} width={stageSize.width} height={stageSize.height} draggable dragBoundFunc={dragBoundFunc}>
          <Layer ref={layerRef}/>
        </Stage>
      </Card>
    </div>
  )
}

export default KonvaFuncTest